﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Emporium_Web.Controls
{
    /// <summary>
    /// Control de paginación genérico para grillas
    /// </summary>
    public partial class Pager : System.Web.UI.UserControl
    {
        /// <summary>
        /// Método delegado del evento "PageChanged"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public delegate void PageChangedEventHandler(object sender, DataNavigatorEventArgs e);

        private string _strButtonCSSClass;
        private string _strCSSFooterDisplayClass;
        private string _strTextBoxCSSClass;

        public string CSSFooterDisplayClass
        {
            get { return _strCSSFooterDisplayClass; }

            set { _strCSSFooterDisplayClass = value; }
        }

        public short CurrentPage
        {
            get
            {
                if (ViewState[ID + "CurrentPage"] == null)
                    ViewState[ID + "CurrentPage"] = (short)1;
                return (short)ViewState[ID + "CurrentPage"];
            }
            private set
            {
                txtPageNumber.Text = value.ToString();
                ViewState[ID + "CurrentPage"] = value;
            }
        }

        public byte PageSize
        {
            get { return (byte)(ViewState[ID + "PageSize"] ?? (byte)10); }
            set { ViewState[ID + "PageSize"] = value; }
        }

        public int TotalRowCount
        {
            get { return (int)(ViewState[ID + "TotalRowCount"] ?? 0); }
            set { ViewState[ID + "TotalRowCount"] = value; }
        }

        private short TotalPages
        {
            get
            {
                short result;

                if (TotalRowCount % PageSize == 0)
                {
                    result = (short)(TotalRowCount / PageSize);
                }
                else
                {
                    result = (short)((TotalRowCount / PageSize) + 1);
                }

                return result;
            }
        }

        public string CSSButtonClass
        {
            get { return _strButtonCSSClass; }

            set { _strButtonCSSClass = value; }
        }

        public string CSSTextBoxClass
        {
            get { return _strTextBoxCSSClass; }
            set { _strTextBoxCSSClass = value; }
        }

        public event PageChangedEventHandler PageChanged;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Put user code to initialize the page here
            btnGo.CssClass = CSSButtonClass;
            txtPageNumber.CssClass = CSSTextBoxClass;
            tdFooterDisplay.Attributes.Add("class", CSSFooterDisplayClass);
            lblOf.Text = "de";
            lblPage.Text = "Página";
            btnGo.Text = "Ir";

            //if (!Page.IsPostBack)
            //{
            //    this.txtPageNumber.Text = this.CurrentPage.ToString();
            //    this.lblTotalPages.Text = this.TotalPages.ToString();
            //    this.lblCurrentPageNumber.Text = this.CurrentPage.ToString().Trim();

            //    //ClientScript.RegisterClientScriptBlock(this.GetType(), "NoEnter", "<script type='text/javascript'>function noenter() {return !(window.event && window.event.keyCode == 13);}</script>");

            //    //se le añade la validacion de tecla Enter a las cajas de texto correspondientes
            //    //txtPageNumber.Attributes.Add("onkeypress", "javascript:return noenter()");
            //}
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (TotalPages <= 1)
            {
                pagerContainer.Visible = false;
            }
            else
            {
                short currentPage = CurrentPage;
                short totalPages = TotalPages;

                pagerContainer.Visible = true;
                txtPageNumber.Text = currentPage.ToString();
                lblTotalPages.Text = totalPages.ToString();
                lblCurrentPageNumber.Text = currentPage.ToString().Trim();

                lnk_First.Visible = (currentPage != 1);
                lnkPrev.Visible = (currentPage != 1);
                lnkNext.Visible = (currentPage != totalPages);
                lnkLast.Visible = (currentPage != totalPages);
                RegularExpressionValidator1.MaximumValue = totalPages.ToString();

                lblCurrentPageNumber.Text = currentPage.ToString();
            }
        }

        /// <summary>
        /// Método del evento "PageChanged"
        /// </summary>
        /// <param name="args"></param>
        protected void OnPageChanged(DataNavigatorEventArgs args)
        {
            if (PageChanged != null)
            {
                PageChanged(this, args);
            }
        }
        
        /// <summary>
        /// Retorna a la primera página
        /// </summary>
        public void Reset()
        {
            CurrentPage = 1;
        }

        /// <summary>
        /// Método para actualizar la página. Lanza el evento "PageChanged" al nivel superior
        /// </summary>
        /// <param name="pageNumber"></param>
        protected void UpdatePage(short pageNumber)
        {
            var args = new DataNavigatorEventArgs();

            args.CurrentPage = pageNumber;
            args.TotalPages = TotalPages;

            CurrentPage = pageNumber;

            OnPageChanged(args);
        }

        /// <summary>
        /// Activa uno de los comandos del control (FirstPage, PreviousPage, NextPage, LastPage)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnk_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "First":
                    CurrentPage = 1;
                    txtPageNumber.Text = CurrentPage.ToString();
                    UpdatePage(CurrentPage);

                    break;
                case "Previous":
                    //Validamos no estar en la primera
                    if (CurrentPage > 1)
                    {
                        CurrentPage--;
                        txtPageNumber.Text = CurrentPage.ToString();
                        UpdatePage(CurrentPage);
                    }
                    break;
                case "Next":
                    //Validamos no estar en la última página
                    if (CurrentPage < TotalPages)
                    {
                        CurrentPage++;
                        txtPageNumber.Text = CurrentPage.ToString();
                        UpdatePage(CurrentPage);
                    }
                    break;
                case "Last":
                    CurrentPage = TotalPages;
                    txtPageNumber.Text = CurrentPage.ToString();
                    UpdatePage(CurrentPage);
                    break;
            }
        }

        protected void btnGo_Click(object sender, EventArgs e)
        {
            UpdatePage(Int16.Parse(txtPageNumber.Text));
        }
    }
    /// <summary>
    /// Estructura de datos para eventos de navegación
    /// </summary>
    public class DataNavigatorEventArgs : EventArgs
    {
        private short m_iCurrentPage;
        private int m_iTotalPages;
        /// <summary>
        /// Página actual
        /// </summary>
        public short CurrentPage
        {
            get { return m_iCurrentPage; }
            set { m_iCurrentPage = value; }
        }
        /// <summary>
        /// Total de páginas
        /// </summary>
        public int TotalPages
        {
            get { return m_iTotalPages; }
            set { m_iTotalPages = value; }
        }
    }
}